import { login, logout, getMenu } from '@/api/admin'
import { getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import defAva from '@/assets/images/profile.jpg'
import { defineStore } from 'pinia'
import {ElMessage} from 'element-plus';
import router from "../router/index"


const useUserStore = defineStore('user', {
	state: () => ({
		token: getToken(),
		id: '',
		name: '',
		avatar: '',
		roles: [],
		permissions: [],
		userinfo: {
            token: localStorage.getItem("ft-token"),
            userId: null,
            username: '',
            avatar: '',
            credential: {},
            permissions: []
        },
		menuInfo: []
	}),
	actions: {
		// 登录
		login(userInfo: any) {
			const username = userInfo.username.trim()
			const password = userInfo.password
			return new Promise((resolve, reject) => {
				login(username, password)
					.then(async (res) => {
						ElMessage.success('登录成功');
						setToken(res.data.token)
						this.userinfo = res.data
						this.setUserinfo(res.data)
						this.token = res.data.token
						router.push('/');
						resolve(undefined)
					})
					.catch((error) => {
						reject(error)
					})
			})
		},
		setUserinfo(d: any) {
            this.userinfo = d;
			localStorage.setItem("userinfo", JSON.stringify(d));
        },
		setMenuinfo(menu: any) {
            this.menuInfo = menu;
			localStorage.setItem("menuinfo", JSON.stringify(menu));
        },
		// 获取用户信息
		getInfo() {
			return new Promise((resolve, reject) => {
				getInfo()
					.then((res) => {
						const user = res.data.user
						const avatar = user.avatar == '' || user.avatar == null ? defAva : user.avatar

						if (res.data.roles && res.data.roles.length > 0) {
							// 验证返回的roles是否是一个非空数组
							this.roles = res.data.roles
							this.permissions = res.data.permissions
						} else {
							this.roles = ['ROLE_DEFAULT'] as any
						}
						this.id = user.userId
						this.name = user.userName
						this.avatar = avatar
						resolve(res)
					})
					.catch((error) => {
						reject(error)
					})
			})
		},
		// 退出系统
		logOut() {
			return new Promise((resolve, reject) => {
				logout().then(() => {
					// const router = useRouter()
					localStorage.removeItem('token');
					this.token = ''
					this.roles = []
					this.permissions = []
					removeToken()
					router.push('/login');
					resolve(undefined)
				})
				.catch((error) => {
					reject(error)
				})
			})
		}
	},
})

export default useUserStore
